<template>
	<m-layout class="farm" title="" color="#fff" gap="0 24" :goBack="false" barBg="unset">
		<view slot="back">
			<m-image2 :size="[198, 40]" src="../../static/images/pages/farm/farmTop.png" />
		</view>
		<view slot="right" class="flex" @click="Jump('/pages/farm/record/index')">
			<m-icon type="recive" size="40" />
			<text class="fs24 ml-4 text-black">領取記錄</text>
		</view>
		<view class="flex-column">
			<view class="flex mb-20">
				<m-icon type="coin" size="30" />
				<text class="fs22 ml-12">歡迎來到農場，快人一步，解鎖專屬獎勵！</text>
			</view>
			<m-block class="totalCount flex fs26 pl-20 jc-center">
				<m-icon type="coin2" size="30" />
				<text class="mlr-12">累計已收穫</text>
				<view class="flex">
					<text>{{ receiveData.receiveCount }}</text>
					<text class="ml-4">果實</text>
				</view>
			</m-block>
			<view class="imgBox flex-column jc-center plr-32 pt-300">
				<m-image2 :size="[627, 653]" src="../../static/images/pages/farm/tree.png" />
				<text class="fs21 farmState flex jc-center" :class="[receiveData.state == 1 ? '' : 'text-red']">
					{{ receiveData.state == 1 ? '生產中...' : '已結束' }}
				</text>
			</view>
			<view class="btnBox flex-column mt-20">
				<view class="flex jc-center fs24 mtb-12 text-white" v-if="receiveData.receiveNext">
					<text>下一次領取:</text>
					<view class="flex">
						<text>{{ receiveData.receiveNext.replace('T', ' ').slice(0, 16)}}</text>
					</view>
				</view>
				<view class="recBtn flex jc-center ai-baseline pt-24" @click="handleUseFeature()">
					<view class="flex" v-if="Number(startTime)>0">
						<mCountDown color="#fff" :timestamp="startTime" />
					</view>
					<view class="flex text-white" v-else>
						<text v-if="receiveData.receive == 1">領取</text>
					</view>
					<text class="fs26 ml-8 text-white">{{ receiveData.receiveNum }}</text>
					<text class="fs24 text-white">果實</text>
				</view>
			</view>
		</view>
		<m-dialog title="" :showCancel="false" :isShow="tipsShow" @handleCancel="tipsShow = false"
			@handleConfirm="tipsShow = false">
			<view class="ptb-48 flex-column jc-center ai-center">
				<m-image2 :size="[260, 260]" src="../../static/images/pages/farm/success.png" />
				<text>領取成功</text>
				<view class="flex text-primary fs26 mt-12">
					<text>收穫</text>
					<text>{{ receiveData.receiveNum }}</text>
					<text class="fs24">果實</text>
				</view>
			</view>
		</m-dialog>
		<!-- <ad-rewarded-video ref="adRewardedVideo" adpid="1507000689" :preload="false" :loadnext="false" :disabled="true"
			v-slot:default="{loading, error}" @load="onadload" @close="onadclose" @error="onaderror">
			<view class="ad-error" v-if="error">{{error}}</view>
		</ad-rewarded-video>
		<button type="primary" :disabled="isLoadingAd" :loading="isLoadingAd" @click="showAd">显示广告</button> -->
	</m-layout>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import {
		myFruit,
		Receive
	} from '@/api/Activetion.js';
	import {
		creditdetal
	} from '@/api/Trade.js';
	import mCountDown from '@/components/m-countdown/index.vue';
	export default {
		components: {
			mCountDown
		},
		data() {
			return {
				credittype: '41', // 农场收益
				receiveData: {},
				typeid: 1,
				listArr: [],
				pageIndex: 1,
				pageSize: 10,
				pageCount: 1,
				isLoading: false,
				startTime: 0,
				tipsShow: false,
				_rewardedVideoAd: null,
				_isLoadedAd: false,
				_isApp: false // 是否为App环境
			};
		},
		onLoad() {},
		onReady() {
			// 检测运行环境
			this._checkEnvironment();

			if (this._isApp) {
				this._initRewardedVideoAd();
			} else {
				console.log('当前为H5环境，不支持激励视频广告');
			}
		},
		computed: {
			...mapState({
				coinConfig: (state) => state.general.coinConfig,
				config: (state) => state.general.config,
				timespan: (state) => state.general.timespan
			})
		},
		onShow() {
			this.reset();
		},
		methods: {
			/**
			 * 检测运行环境
			 */
			_checkEnvironment() {
				// 方法1：检测平台
				const platform = uni.getSystemInfoSync().platform;
				console.log('platform', platform)
				this._isApp = platform === 'android' || platform === 'ios';

				// // 方法2：检测API是否存在
				// if (typeof uni.createRewardedVideoAd === 'function') {
				// 	this._isApp = true;
				// }

				console.log('运行环境:', this._isApp ? 'App' : 'H5');
			},

			/**
			 * 初始化激励视频广告（仅App环境）
			 */
			_initRewardedVideoAd() {
				if (!this._isApp) {
					console.log('H5环境不支持激励视频广告');
					return;
				}

				this._isLoadedAd = false;

				this._rewardedVideoAd = uni.createRewardedVideoAd({
					adpid: '1507000689',
					urlCallback: {
						userId: 'testuser',
						extra: 'testdata'
					}
				});

				this._bindAdEvents();
			},

			/**
			 * 绑定广告事件
			 */
			_bindAdEvents() {
				if (!this._rewardedVideoAd) return;

				this._rewardedVideoAd.onLoad(() => {
					this._isLoadedAd = true;
					console.log('✅ 激励视频广告加载成功');
				});

				this._rewardedVideoAd.onError((err) => {
					this._isLoadedAd = false;
					console.error('❌ 激励视频广告加载失败:', err);
				});

				this._rewardedVideoAd.onClose((res) => {
					console.log('📱 激励视频广告关闭:', res);
					this._handleAdClose(res);
				});
			},

			/**
			 * 显示广告（带环境检测）
			 */
			async showRewardedVideoAd() {
				if (!this._isApp) {
					// H5环境降级处理
					this._handleH5Fallback();
					return false;
				}

				// 如果未初始化，自动初始化
				if (!this._rewardedVideoAd) {
					console.log('广告未初始化，正在自动初始化...');

					try {
						await this._initRewardedVideoAd();
					} catch (err) {
						console.error('自动初始化失败:', err);
						this._handleInitError();
						return false;
					}
				}

				// 检查是否加载完成
				if (!this._isLoadedAd) {
					uni.showLoading({
						title: '廣告加載中...'
					});

					try {
						await this._waitForAdLoad();
						uni.hideLoading();
					} catch (err) {
						uni.hideLoading();
						this._handleLoadError();
						return false;
					}
				}

				// 显示广告
				try {
					await this._rewardedVideoAd.show();
					return true;
				} catch (err) {
					console.error('显示广告失败:', err);
					this._handleShowError();
					return false;
				}
			},

			/**
			 * 等待广告加载完成
			 */
			_waitForAdLoad(timeout = 10000) {
				return new Promise((resolve, reject) => {
					const timer = setTimeout(() => {
						reject(new Error('广告加载超时'));
					}, timeout);

					const checkLoad = () => {
						if (this._isLoadedAd) {
							clearTimeout(timer);
							resolve();
						} else {
							setTimeout(checkLoad, 100);
						}
					};

					checkLoad();
				});
			},

			/**
			 * 处理广告错误（用户友好版本）
			 */
			_handleAdError(err, retryCount = 0, maxRetries = 3) {
				let title = '';
				let content = '';
				let showRetry = false;

				// 根据错误类型和重试次数决定处理方式
				if (retryCount < maxRetries) {
					// 还有重试机会
					title = '廣告加載中';
					content = '請稍候，正在為您準備廣告...';
					showRetry = true;
				} else {
					// 重试次数用完
					if (err.message.includes('未初始化')) {
						title = '功能暫時不可用';
						content = '廣告服務正在維護中，本次免費使用';
					} else if (err.message.includes('网络')) {
						title = '網絡異常';
						content = '请检查网络连接后重试';
						showRetry = true;
					} else {
						title = '廣告暫時無法播放';
						content = '本次免費使用，感謝您的理解';
					}
				}

				// 显示用户友好的提示
				uni.showModal({
					title: title,
					content: content,
					showCancel: showRetry,
					confirmText: showRetry ? '重試' : '確定',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm && showRetry) {
							// 用户选择重试
							this.showRewardedVideoAd(retryCount + 1);
						} else if (!showRetry) {
							// 降级处理：允许用户使用功能
							this.receiveDataFn();
						}
					}
				});
			},
			/**
			 * H5环境降级处理
			 */
			_handleH5Fallback() {
				uni.showModal({
					title: '提示',
					content: '此功能需要在App中使用，请下载App体验完整功能',
					confirmText: '下载App',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							// this._guideToDownloadApp();
						}
					}
				});
			},
			/**
			 * 处理广告关闭
			 */
			_handleAdClose(res) {
				if (res && res.isEnded) {
					console.log('✅ 用户观看完整广告');
					uni.showToast({
						title: '觀看完成，獎勵領取中！',
						icon: 'success'
					});
					this.ReceiveFn();
				} else {
					console.log('❌ 用户未观看完整');
					uni.showToast({
						title: '需要觀看完整廣告才能獲得獎勵',
						icon: 'none'
					});
				}
			},

			/**
			 * 用户点击使用功能
			 */
			async handleUseFeature() {
				if (this.receiveData.receive !== 1) return this.Toast('未到领取时间');
				if (!this._isApp) {
					// H5环境直接提示
					this._handleH5Fallback();
					return;
				}

				// App环境显示广告
				const confirm = await this.showConfirm(
					'觀看30秒廣告即可領取果實'
				);

				if (!confirm) return;

				const success = await this.showRewardedVideoAd();

				if (!success) {
					console.log('广告显示失败');
				}
			},

			/**
			 * 显示确认弹窗
			 */
			showConfirm(content) {
				return new Promise((resolve) => {
					uni.showModal({
						title: '提示',
						content: content,
						confirmText: '觀看廣告',
						cancelText: '取消',
						success: (res) => {
							resolve(res.confirm);
						}
					});
				});
			},
			// showAd() {
			// 	if (this.isLoadingAd) return;
			// 	this.$refs.adRewardedVideo.show();
			// },
			onadload(e) {
				this.isLoadingAd = false;
				console.log('广告数据加载成功');
			},
			onadclose(e) {
				const detail = e.detail
				// 用户点击了【关闭广告】按钮
				if (detail && detail.isEnded) {
					// 正常播放结束
					console.log("onClose " + detail.isEnded);
				} else {
					// 播放中途退出
					console.log("onClose " + detail.isEnded);
				}
				//this.isLoading = true;
				//this.$refs.adRewardedVideo.load();
			},
			onaderror(e) {
				// 广告加载失败
				console.log(e.detail);
				this.isLoadingAd = false;
			},
			// 初始化
			reset() {
				this.pageCount = 1;
				this.pageIndex = 1;
				this.receiveDataFn();
				this.getData();
			},
			getTimestamp(timeStr) {
				const timestamp = Math.floor(new Date(timeStr).getTime() / 1000);
				this.startTime = Number(timestamp) - this.timespan;
			},
			async ReceiveFn() {
				const {
					success,
					msg
				} = await Receive();
				this.Toast(msg);
				if (!success) return;
				this.tipsShow = true;
				this.reset();
			},
			async receiveDataFn() {
				const {
					success,
					msg,
					data
				} = await myFruit();
				this.receiveData = data;
				this.getTimestamp(data.receiveNext);
			},
			// 获取转让记录列表
			async getData() {
				if (this.pageIndex > this.pageCount) return;
				this.isLoading = true;
				const {
					list,
					pageCount,
					success
				} = await creditdetal({
					credittype: this.credittype,
					pageSize: this.pageSize,
					pageIndex: this.pageIndex
				});
				this.isLoading = false;
				this.pageCount = pageCount;
				if (this.pageIndex <= 1) {
					this.listArr = list;
				} else {
					this.listArr = [...this.listArr, ...list];
				}
				this.pageIndex++;
				uni.stopPullDownRefresh();
			}
		},
		onPullDownRefresh() {
			this.reset();
		},
		onReachBottom() {
			this.getData();
			console.log('触底了');
		}
	};
</script>

<style lang="scss">
	page {
		height: 100%;
		background: url('../../static/images/pages/farm/farmbg.png') no-repeat;
		background-size: 100% 100%;
		padding: 0rpx 0rpx;
		box-sizing: border-box;
	}

	.totalCount {
		height: 60rpx;
		background: rgba(34, 92, 243, 0.15);
		border-radius: 30px;
	}

	.rewardBox {
		background: url('../../static/images/pages/farm/block_bg.png') no-repeat;
		background-size: 100% 100%;
	}

	.recordBox {
		// background: url('../../static/images/pages/farm/block_bg.png') no-repeat;
		background-size: 100% 100%;
		min-height: 500rpx;
	}

	.reciveBtn {
		width: 100%;
		height: 90rpx;
		background: linear-gradient(0deg, #3362f9 0%, #48a2ff 100%);
		border-radius: 15rpx;
	}

	.animationBox {
		margin-top: 20rpx;
		background: url('../../static/images/pages/farm/bg01.png') no-repeat;
		height: 420rpx;
		background-size: 100% 100%;
	}

	.farmState {
		width: 159rpx;
		height: 47rpx;
		background: #277511;
		border-radius: 20rpx;
		color: #fff;
	}

	.btnBox {
		.recBtn {
			background: url('../../static/images/pages/farm/recBtn.png') no-repeat;
			background-size: 100% 115rpx;
			height: 115rpx;
		}
	}

	.imgBox {
		position: relative;

		.farmState {
			position: absolute;
			bottom: 150rpx;
			left: 50%;
			transform: translate(-50%);
		}
	}
</style>